﻿using NxStoreManage;

using System;

namespace LengthAiCalculate
{
    public partial class ChangeAbandonSmall : BaseForm
    {
        public ChangeAbandonSmall()
        {
            InitializeComponent();
        }

        private string id = "0";
        public Action SucAction;

        public void SetInfo(string id, string zzph, string steelClassName, string sizeName, string length, string cutNum)
        {
            this.id = id;
            label2.Text = zzph;
            label4.Text = sizeName;
            label6.Text = steelClassName;
            label8.Text = length;
            label10.Text = cutNum;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int num = 0;
            if (!int.TryParse(textBox1.Text.Trim(), out num) || num < 0)
            {
                ShowError("请输入正确的改尺支数,！");
                return;
            }
            int oldNum = 0;
            int.TryParse(label10.Text.Trim(), out oldNum);
            if (num > oldNum)
            {
                ShowError("改尺支数不能大于锯切支数！");
                return;
            }
            string itemKey = Guid.NewGuid().ToString("N");
            string outKeyCode, gglb;
            var dt = nxsqlHelper.GetDataTableFromSql(@"SELECT [outKeyCode], [gglb] FROM [PM.ManualManufactureResultGroupZZPH] WHERE id=" + id);
            if (dt.Rows.Count == 0)
            {
                ShowError("未找到对应的锯切信息，请刷新后重试！");
                return;
            }
            else
            {
                outKeyCode = dt.Rows[0]["outKeyCode"].ToString();
                gglb = dt.Rows[0]["gglb"].ToString();
            }
            string sql = $@"BEGIN TRAN;INSERT INTO [PM.ManualManufactureResultGroupZZPHItem]
                    (
                        itemKey,
                        cutNum,
                        createUser,
                        createDate,
                        createType
                    )
                    SELECT itemKey,
                           -{num},
                           '{LoginUser.LoginUserName}',
                           GETDATE(),
                           3
                    FROM [PM.ManualManufactureResultGroupZZPH]
                    WHERE id = {id};
                    UPDATE [PM.ManualManufactureResultGroupZZPH]
                    SET cutNum = cutNum - {num}
                    WHERE id = {id};IF @@ERROR=0 COMMIT TRAN ELSE ROLLBACK TRAN";
            if (nxsqlHelper.ExcuteSql(sql) > 0)
            {
                ShowMsg("操作成功！");
                SucAction?.Invoke();
                this.Close();
            }
            else
            {
                ShowError("操作失败，请稍后重试！");
            }
        }
    }
}